package com.ziyun.pop.rest.module.login;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.service.common.utils.Md5Util;
import com.ziyun.pop.common.token.RedisTokenManager;
import com.ziyun.pop.common.utils.UserUtils;
import com.ziyun.pop.modules.supp.service.SellerInfoService;
import io.renren.common.exception.RRException;
import io.renren.common.utils.R;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import io.renren.modules.sys.shiro.ShiroUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Api(value = "LoginRestApi", tags = "登录服务")
@RestController
@RequestMapping("popApi/sys/")
public class LoginRestApi {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private RedisTokenManager redisTokenManager;

    @Autowired
    private SellerInfoService sellerInfoService;

    @ApiOperation(value = "登录")
    @ApiResponses(value = @ApiResponse(code = 200, message = "操作成功"))
    @PostMapping("/loginApi")
    public R loginApi(@RequestBody Map<String, Object> map, HttpServletRequest request) {
        String userName = (String) map.get("userName");
        String password = (String) map.get("password");
        SysUserEntity sysUserEntity = this.sysUserService.getOne(new QueryWrapper<SysUserEntity>()
                .eq("username", userName));
        if (sysUserEntity != null && sysUserEntity.getUserId() != null) {
            // 用户名密码正确
            // 再校验密码
            if (ShiroUtils.validatePassword(password, sysUserEntity.getPassword())) {
                //request.getSession().setAttribute("popUserInfo",JsonUtils.object2String(sysUserEntity));
                Map<String, Object> rs = new HashMap<>();
                rs.put("popUserInfo", sysUserEntity);
                rs.put("token", redisTokenManager.createToken(sysUserEntity));
                rs.put("expireTime", redisTokenManager.getExpireTime());
                return R.apiOk(rs);

            } else {
                return R.apiError(0, "密码错误");
            }
        } else {
            return R.apiError(0, "用户名错误,或不存在!");
        }
    }

    @ApiOperation(value = "绑定微信OpenId")
    @ApiResponses(value = @ApiResponse(code = 200, message = "操作成功"))
    @PostMapping("/relationOpenIdApi")
    public R relationOpenIdApi(@RequestBody Map<String, Object> map) {
        SysUserEntity sysUserEntity = UserUtils.getCurentUser();
        if (map.get("openId") == null) {
            throw new RRException("openId 不能为空!");
        }
       /* if (map.get("uuid") == null) {
            throw new RRException("uuid 不能为空!");
        }*/
        String openId = map.get("openId").toString();
        // 一个sellerId 只能绑定 一个openId
        int count = this.sysUserService.count(new QueryWrapper<SysUserEntity>()
                .eq("seller_id", sysUserEntity.getSellerId())
                .isNotNull("open_id")
        );
        if (count >0){
            throw new RRException("该商家已经有人员绑定OpenId!");
        }
        this.sysUserService.update(sysUserEntity, new UpdateWrapper<SysUserEntity>()
                .set("open_id", openId)
                .set("uuid", map.get("uuid"))
                .eq("user_id", sysUserEntity.getUserId()));

        return R.apiOk("绑定成功!");
    }

    @ApiOperation(value = "解绑微信OpenId")
    @ApiResponses(value = @ApiResponse(code = 200, message = "操作成功"))
    @PostMapping("/relieveOpenIdApi")
    public R relieveOpenIdApi() {
        SysUserEntity sysUserEntity = UserUtils.getCurentUser();
        this.sysUserService.update(sysUserEntity, new UpdateWrapper<SysUserEntity>()
                .set("open_id", null)
                .set("uuid", null)
                .eq("user_id", sysUserEntity.getUserId()));

        return R.apiOk("解绑成功!");
    }

    @ApiOperation(value = "微信OpenId登陆")
    @ApiResponses(value = @ApiResponse(code = 200, message = "操作成功"))
    @PostMapping("/loginByOpenIdApi")
    public R loginByOpenIdApi(@RequestBody Map<String, Object> map) {
        if (map.get("openId") == null) {
            throw new RRException("openId 不能为空!");
        }
        String openId = map.get("openId").toString();
        SysUserEntity sysUserEntity = this.sysUserService.getOne(new QueryWrapper<SysUserEntity>()
                .eq("open_id", openId));
        if (sysUserEntity != null && sysUserEntity.getUserId() != null) {
            Map<String, Object> rs = new HashMap<>();
            rs.put("popUserInfo", sysUserEntity);
            rs.put("token", redisTokenManager.createToken(sysUserEntity));
            rs.put("expireTime", redisTokenManager.getExpireTime());
            return R.apiOk(rs);
        } else {
            String uuid = map.get("uuid").toString();
            // 生成默认 pop_sys_user 以及user_base_info
            SysUserEntity sysUser = this.sellerInfoService.initUserWithOpenId(openId,uuid);
            Map<String, Object> rs = new HashMap<>();
            rs.put("popUserInfo", sysUser);
            rs.put("token", redisTokenManager.createToken(sysUser));
            rs.put("expireTime", redisTokenManager.getExpireTime());
            return R.apiOk(rs);
        }
    }

    @ApiOperation(value = "重置密码")
    @ApiResponses(value = @ApiResponse(code = 200, message = "操作成功"))
    @PostMapping("/resetPasswordApi")
    public R resetPasswordApi(@RequestBody Map<String, Object> map) {
        SysUserEntity sysUser = UserUtils.getCurentUser();
        String oldPassword = map.get("oldPassword").toString();
        String newPassword = map.get("newPassword").toString();

        // 校验 旧密码
        //判断旧密码是否正确
        if (ShiroUtils.validatePassword(oldPassword, sysUser.getPassword())){
            this.sysUserService.updatePassword(sysUser.getUserId(), newPassword);
            return R.apiOk("更改成功!");
        }else {
            return R.apiError(0,"原密码不正确");
        }
    }


}
